import Foundation

struct HostURLParser {
  /// 解析宿主 App 收到的 URL
  /// - Parameter url: 接收到的 URL
  /// - Returns: ParsedResult，包含 page 和 params
  static func parse(url: URL) -> WXShareModel? {
    guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
      let queryItems = components.queryItems
    else {
      print("HostURLParser: 无法解析 URL")
      return nil
    }

    var params: [String: String] = [:]

    for item in queryItems {
      if let value = item.value {
        params[item.name] = value
      }
    }

    if let schema = components.scheme,
      schema != "BaoDanEx"
    {
      return nil
    }

    if let page = params["page"],
      page != "share"
    {
      return nil
    }

    let decoder = JSONDecoder()
    do {
      let jsonData = try JSONSerialization.data(withJSONObject: params, options: [])
      let response = try decoder.decode(WXShareModel.self, from: jsonData)
      return response
    } catch {
      print(error)
      return nil
    }
  }
}
